// es6版本
class Single {
    show() {
        console.log("我是一个单例对象")
    }
    static getInstance() {
        if (!Single.instance) {
            Single.instance = new Single()
        }
        return Single.instance
    }
}

let s1 = Single.getInstance()
let s2 = Single.getInstance()

console.log(s1 == s2, s1, s2) // true
// es6第二种方式
class Singleton{
    constructor(name){
        if(!Singleton.instance){
            this.name = name
            Singleton.instance = this
        }
        return Singleton.instance
    }
     
    toString(){
        return '[object Singleton]'
    }
}


// es5 第一种方式

let SingleObj = (function() {
	let instance
	return function() {
		if(instance) {
			return instance
		} else {
			// this.name = "Join"
			instance = this
		}
	}
}())

let s3 = new SingleObj()
let s4 = new SingleObj()


console.log(s3, s4, s3 === s4)

// es5 第二种方式

var createDiv = function (html) {
    this.html = html
    this.init()
}

createDiv.prototype.init = function () {
    var div = document.createElement("div")
    div.innerHTML = this.html
    document.body.appendChild(div)
}

var createDivSingle = (function () {
    var instance;
    return function (html) {
        if (instance) {
            return instance
        } else {
            instance = new createDiv(html)
        }
    }
})()

var s5 = new createDivSingle("45646")
var s6 = new createDivSingle()

console.log(s5, s6, s5 === s6)

// 惰性单例模式
let getSingle=(function(){
    let single;
    return function(fn){
        return single||(single=fn.apply(this,arguments))
    }
})();
function creatDom(){
    let dom=document.createElement('div');
    dom.style.display='none';
    document.body.appendChild(dom);
    return dom;
}
let Alerts=(function(){
    let instance=null;
    let dom;
    function Alert(content){
        instance=instance||(
            this instanceof Alert?this:new Alert(content)
        )
        instance.init(content);
        return instance;
    }
    Alert.prototype.init=function(content){
        dom=getSingle(creatDom);
        dom.style.display='block';
        dom.innerText=content;
    };
    Alert.prototype.hide=function(content){
        dom.style.display='none'
    };
    return Alert;
})();
